#include "pika_platform_thread.h"
#define LOG pika_platform_printf





//----------------------------- cond -------------------------------

int pika_platform_thread_cond_init(pika_platform_thread_cond_t* cond){
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    pika_platform_thread_rlock_init(&cond->rtmutex);
    pthread_cond_init(&cond->cond, NULL);
    cond->owner = (pthread_t)0;

#elif PIKA_FREERTOS_ENABLE
    PIKA_ASSERT_1(cond != NULL)
    // if (cond == NULL) return PIKA_RES_ERR_ASSERT;

    cond->mutex = xSemaphoreCreateRecursiveMutex();
    if (cond->mutex == NULL) return PIKA_RES_ERR_MEMORY_ERROR;

    cond->semaphore = xSemaphoreCreateCounting(MAX_WAITING_THREADS, 0);
    if (cond->semaphore == NULL) {
        vSemaphoreDelete(cond->mutex);
        return PIKA_RES_ERR_MEMORY_ERROR;
    }
    cond->waiting_threads = 0;
    return PIKA_RES_OK;
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}

void pika_platform_thread_cond_destory(pika_platform_thread_cond_t* cond) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    pthread_cond_destroy(&cond->cond);
    pika_platform_thread_rlock_destroy(&cond->rtmutex);
    cond->owner = (pthread_t)0;  // 释放资源后重置 owner
#elif PIKA_FREERTOS_ENABLE
    if (cond->mutex != NULL){
        vSemaphoreDelete(cond->mutex);
        cond->mutex = NULL;
    }
    if (cond->semaphore != NULL){
        vSemaphoreDelete(cond->semaphore);
        cond->semaphore = NULL;
    }
    
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif

}

// 获取锁
int pika_platform_thread_cond_acquire(pika_platform_thread_cond_t *cond, pika_bool block, pika_float timeout) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
#elif PIKA_FREERTOS_ENABLE
    PIKA_ASSERT_1(cond != NULL && cond->mutex != NULL && cond->semaphore != NULL)
    // if (cond == NULL || cond->mutex == NULL || cond->semaphore == NULL) return PIKA_RES_ERR_ASSERT;
    
    TickType_t ticksToWait;
    if (block){
        // 处理不同类型的timeout
        if (timeout > 0.0f) {
            // 浮点型，大于0：带阻塞超时的功能
            ticksToWait = (TickType_t)(timeout * configTICK_RATE_HZ);
        } else if (timeout == 0.0f) {
            // 等于0：立即返回获取锁的结果，不阻塞
            ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
        } else {
            ticksToWait = portMAX_DELAY;
        }
    }
    else{
        ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
    }
    pika_GIL_EXIT();
    // 获取互斥信号量
    BaseType_t result = xSemaphoreTakeRecursive(cond->mutex, ticksToWait);
    pika_GIL_ENTER();
    if (result == pdTRUE){
        return PIKA_RES_OK;
    }
    else if (result == pdFALSE && ticksToWait > 0) {
        return PIKA_RES_ERR_TIMEOUT;
    }
    else{
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}

int pika_platform_thread_cond_release(pika_platform_thread_cond_t *cond) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
#elif PIKA_FREERTOS_ENABLE
    // 释放互斥信号量并等待事件
    BaseType_t res = xSemaphoreGiveRecursive(cond->mutex);
    if (res != pdTRUE) return PIKA_RES_ERR_RUNTIME_ERROR;
    return PIKA_RES_OK;
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_ASSERT;
#endif
}

// 带阻塞和超时功能的条件变量等待
int pika_platform_thread_cond_wait(pika_platform_thread_cond_t *cond, pika_float timeout) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    ArgType timout_type = arg_getType(timeout);
    pika_float timeout_f;
    int result;

    // 检查是否已经获得了互斥锁
    if (!is_mutex_owned(cond)) {
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }

    if (!(timout_type == ARG_TYPE_FLOAT || timout_type == ARG_TYPE_INT || timout_type == ARG_TYPE_NONE)) {
        return PIKA_RES_ERR_INVALID_PARAM;
    }

    if (timout_type == ARG_TYPE_FLOAT || timout_type == ARG_TYPE_INT) {
        if (timout_type == ARG_TYPE_FLOAT) {
            timeout_f = arg_getFloat(timeout);
        } else {
            int timeout_d = arg_getInt(timeout);
            timeout_f = (pika_float)timeout_d;
        }

        if (timeout_f < 0.0f) {
            return PIKA_RES_ERR_INVALID_PARAM;
        }

        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);  // 获取当前时间

        // 将浮点数秒转换为秒和纳秒
        long sec = (long)timeout_f;
        long nsec = (long)((timeout_f - (pika_float)sec) * 1000000000.0);

        ts.tv_sec += sec;
        ts.tv_nsec += nsec;

        // 如果纳秒数超过 1 秒，则需要调整秒数和纳秒数
        if (ts.tv_nsec >= 1000000000) {
            ts.tv_nsec -= 1000000000;  // 减去 1 秒的纳秒数
            ts.tv_sec += 1;            // 增加 1 秒
        }

        // 等待直到被通知或超时
        pika_GIL_EXIT();
        result = pthread_cond_timedwait(&cond->cond, &cond->rtmutex.mutex, &ts);
        pika_GIL_ENTER();

        if (result != 0) {
            if (result == ETIMEDOUT) {
                return PIKA_RES_ERR_RUNTIME_ERROR;  // 超时
            }
            perror("pthread_cond_timedwait");
            return PIKA_RES_ERR_RUNTIME_ERROR;  // 其他错误
        }
    } else if (timout_type == ARG_TYPE_NONE) {
        // 永久等待
        pika_GIL_EXIT();
        result = pthread_cond_wait(&cond->cond, &cond->rtmutex.mutex);
        pika_GIL_ENTER();

        if (result != 0) {
            perror("pthread_cond_wait");
            return PIKA_RES_ERR_RUNTIME_ERROR;
        }
    } else {
        return PIKA_RES_ERR_INVALID_PARAM;
    }

    return PIKA_RES_OK;
    
#elif PIKA_FREERTOS_ENABLE
    PIKA_ASSERT_1(cond != NULL && cond->mutex != NULL && cond->semaphore != NULL)
    // 获取当前任务句柄
    // 获取拥有递归互斥锁的任务句柄
    if (xTaskGetCurrentTaskHandle() != xSemaphoreGetMutexHolder(cond->mutex)){
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }
    TickType_t ticksToWait;
    // 处理不同类型的timeout
    if (timeout > 0.0f) {
        // 浮点型，大于0：带阻塞超时的功能
        ticksToWait = (TickType_t)(timeout * configTICK_RATE_HZ);
    } else if (timeout == 0.0f) {
        // 等于0：立即返回获取锁的结果，不阻塞
        ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
    } else {
        ticksToWait = portMAX_DELAY;
    }

    // 在等待之前，先释放互斥锁
    xSemaphoreGiveRecursive(cond->mutex);
    
    // 增加等待线程计数
    taskENTER_CRITICAL();
    cond->waiting_threads++;
    taskEXIT_CRITICAL();

    // Wait for the condition to be signaled
    pika_GIL_EXIT();
    BaseType_t result = xSemaphoreTake(cond->semaphore, ticksToWait);
    pika_GIL_ENTER();
    // 重新获取互斥锁
    pika_GIL_EXIT();
    xSemaphoreTakeRecursive(cond->mutex, portMAX_DELAY);
    pika_GIL_ENTER();
    
    // 减少等待线程计数
    taskENTER_CRITICAL();
    cond->waiting_threads--;
    taskEXIT_CRITICAL();
    if (result == pdTRUE){
        return PIKA_RES_OK;
    }
    else if (result == pdFALSE && ticksToWait > 0) {
        return PIKA_RES_ERR_TIMEOUT;
    }
    else{
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }

#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_ASSERT;
#endif

}
// 唤醒一个等待该条件变量的线程
int pika_platform_thread_cond_notify(pika_platform_thread_cond_t *cond, int num) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    int result;
    result = pthread_cond_signal(&cond->cond);
    cond->owner = (pthread_t)0;  // 通知后重置 owner
    return result == 0 ? 0 : -1;
#elif PIKA_FREERTOS_ENABLE
    PIKA_ASSERT_1(cond != NULL && cond->mutex != NULL && cond->semaphore != NULL)
    // 检查当前任务是否拥有互斥锁
    if (xTaskGetCurrentTaskHandle() != xSemaphoreGetMutexHolder(cond->mutex)) {
        // 当前线程没有持有互斥锁，返回失败
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }
    size_t threads_to_wake = 0;

    // 获取当前等待线程的数量，并确定要唤醒的线程数量
    taskENTER_CRITICAL();
    threads_to_wake = cond->waiting_threads < (size_t)num ? cond->waiting_threads : (size_t)num;
    taskEXIT_CRITICAL();

    // 增加信号量的计数器，直到所有指定的等待线程都被唤醒
    for (size_t i = 0; i < threads_to_wake; ++i) {
        xSemaphoreGive(cond->semaphore);
    }
    return PIKA_RES_OK;

#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_ASSERT;
#endif
}

// 唤醒所有等待该条件变量的线程
int pika_platform_thread_cond_notify_all(pika_platform_thread_cond_t *cond) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    int result;
    result = pthread_cond_broadcast(&cond->cond);
    cond->owner = (pthread_t)0;  // 广播后重置 owner
    return result == 0 ? 0 : -1;
#elif PIKA_FREERTOS_ENABLE
    PIKA_ASSERT_1(cond != NULL && cond->mutex != NULL && cond->semaphore != NULL)
    // if (cond == NULL || cond->mutex == NULL || cond->semaphore == NULL) return PIKA_RES_ERR_ASSERT;
    // 检查当前任务是否拥有互斥锁
    if (xTaskGetCurrentTaskHandle() != xSemaphoreGetMutexHolder(cond->mutex)) {
        // 当前线程没有持有互斥锁，返回失败
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }

    // 动态调整计数信号量的计数以唤醒所有等待的线程
    size_t threads_to_wake;
    // 获取当前等待线程的数量
    taskENTER_CRITICAL();
    threads_to_wake = cond->waiting_threads;
    taskEXIT_CRITICAL();

    // 增加信号量的计数器，直到所有等待线程都被唤醒
    for (size_t i = 0; i < threads_to_wake; ++i) {
        xSemaphoreGive(cond->semaphore);
    }
    return PIKA_RES_OK;

#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_ASSERT;
#endif
}



//----------------------------- lock -------------------------------


int pika_platform_thread_lock_init(pika_platform_thread_lock_t* m) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    return pthread_mutex_init(&(m->mutex), NULL);
#elif PIKA_FREERTOS_ENABLE
    m->mutex = xSemaphoreCreateMutex();
    if (m->mutex == NULL){
        return PIKA_RES_ERR_MEMORY_ERROR;
    }
    return PIKA_RES_OK;
#elif PIKA_RTTHREAD_ENABLE
    m->mutex = rt_mutex_create("pika_platform_mutex", RT_IPC_FLAG_PRIO);
    return PIKA_RES_OK;
#elif PIKA_ZEUSOS_ENABLE
    static int mutex_count = 0;
    char mutex_name[ZOS_NAME_MAX + 1] = {0};
    zos_sprintf(mutex_name, "pika_mutex%d", mutex_count++);
    m->mutex = zos_mutex_create(mutex_name, ZOS_FALSE);
    return PIKA_RES_OK;
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_ASSERT;
#endif
}


// 带超时的互斥锁加锁
int pika_platform_thread_lock_acquire(pika_platform_thread_lock_t *m, pika_bool block, pika_float timeout) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)    
    ArgType timout_type = arg_getType(timeout);
    pika_float timeout_f;
    int result;
    if (!(timout_type == ARG_TYPE_FLOAT || timout_type == ARG_TYPE_INT || timout_type == ARG_TYPE_NONE)){
        return PIKA_RES_ERR_INVALID_PARAM;
    }

    if (timout_type == ARG_TYPE_FLOAT || timout_type == ARG_TYPE_INT){
        // printf("==== #01\n");
        if (timout_type == ARG_TYPE_FLOAT){
            timeout_f = arg_getFloat(timeout);
        }
        if (timout_type == ARG_TYPE_INT){
            int timeout_d = arg_getInt(timeout);
            timeout_f = (pika_float)timeout_d;
            // printf("==== #04  %lf\n", timeout_f);
        }
        if (timeout_f < 0.0f){
            return PIKA_RES_ERR_INVALID_PARAM;
        }

        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);  // 获取当前时间

        // 将浮点数秒转换为秒和纳秒
        long sec = (long)timeout_f;
        long nsec = (long)((timeout_f - (pika_float)sec) * 1000000000.0);

        ts.tv_sec += sec;
        ts.tv_nsec += nsec;

        // 如果纳秒数超过 1 秒，则需要调整秒数和纳秒数
        if (ts.tv_nsec >= 1000000000) {
            ts.tv_nsec -= 1000000000;  // 减去 1 秒的纳秒数
            ts.tv_sec += 1;            // 增加 1 秒
        }

        pika_GIL_EXIT();
        result = pthread_mutex_timedlock(&m->mutex, &ts);
        pika_GIL_ENTER();
        return result == 0 ? 0 : -1;
        
        
    }
    else if (timout_type == ARG_TYPE_NONE){
        
        if (block) {
            // printf("==== #02\n");
            pika_GIL_EXIT();
            result = pthread_mutex_lock(&m->mutex);
            pika_GIL_ENTER();
            return result == 0 ? 0 : -1;
        }
        else{
            // printf("==== #03\n");
            pika_GIL_EXIT();
            result = pthread_mutex_trylock(&m->mutex);
            pika_GIL_ENTER();
            return result == 0 ? 0 : -1;
        }
    }
    else{
        return PIKA_RES_ERR_INVALID_PARAM;
    }


#elif PIKA_FREERTOS_ENABLE
    TickType_t ticksToWait;
    if (block){
        // 处理不同类型的timeout
        if (timeout > 0.0f) {
            // 浮点型，大于0：带阻塞超时的功能
            ticksToWait = (TickType_t)(timeout * configTICK_RATE_HZ);
        } else if (timeout == 0.0f) {
            // 等于0：立即返回获取锁的结果，不阻塞
            ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
        } else {
            ticksToWait = portMAX_DELAY;
        }
    }
    else{
        ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
    }

    pika_GIL_EXIT();
    BaseType_t result = xSemaphoreTake(m->mutex, ticksToWait);
    pika_GIL_ENTER();
    if (result == pdTRUE){
        return PIKA_RES_OK;
    }
    else if (result == pdFALSE && ticksToWait > 0) {
        return PIKA_RES_ERR_TIMEOUT;
    }
    else{
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }
#elif PIKA_RTTHREAD_ENABLE
    return rt_mutex_take((m->mutex), (rt_tick_t)(timeout * RT_TICK_PER_SECOND));

#elif PIKA_ZEUSOS_ENABLE
    return zos_mutex_lock(m->mutex, (uint32_t)(timeout * 1000.0f));

#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_ASSERT;
#endif
}


int pika_platform_thread_lock_locked(pika_platform_thread_lock_t* m) {
    
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    return pthread_mutex_trylock(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
    if (pdTRUE == xSemaphoreTake(m->mutex, 0)) {
        xSemaphoreGive(m->mutex);
        return PIKA_RES_OK;
    }
    return PIKA_RES_ERR_RUNTIME_ERROR;
#elif PIKA_RTTHREAD_ENABLE
    return rt_mutex_take((m->mutex), 0);
#elif PIKA_ZEUSOS_ENABLE
    return zos_mutex_lock(m->mutex, 0);
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_ASSERT;
#endif
}

int pika_platform_thread_lock_trylock(pika_platform_thread_lock_t* m) {
    
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    return pthread_mutex_trylock(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
    if (pdTRUE == xSemaphoreTake(m->mutex, 0)) {
        return PIKA_RES_OK;
    }
    return PIKA_RES_ERR_RUNTIME_ERROR;
#elif PIKA_RTTHREAD_ENABLE
    return rt_mutex_take((m->mutex), 0);
#elif PIKA_ZEUSOS_ENABLE
    return zos_mutex_lock(m->mutex, 0);
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_RUNTIME_ERROR;
#endif
}

int pika_platform_thread_lock_release(pika_platform_thread_lock_t* m) {
    
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    return pthread_mutex_unlock(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
    return xSemaphoreGive(m->mutex);
#elif PIKA_RTTHREAD_ENABLE
    return rt_mutex_release((m->mutex));
#elif PIKA_ZEUSOS_ENABLE
    return zos_mutex_unlock(m->mutex);
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_RUNTIME_ERROR;
#endif
}

int pika_platform_thread_lock_destroy(pika_platform_thread_lock_t* m) {
    
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    return pthread_mutex_destroy(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
    vSemaphoreDelete(m->mutex);
    return PIKA_RES_OK;
#elif PIKA_RTTHREAD_ENABLE
    return rt_mutex_delete((m->mutex));
#elif PIKA_ZEUSOS_ENABLE
    return zos_mutex_destroy(m->mutex);
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_RUNTIME_ERROR;
#endif
}




//----------------------------- rtmutex -------------------------------
// 初始化递归互斥锁
int pika_platform_thread_rlock_init(pika_platform_thread_rlock_t *rtm) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    pthread_mutexattr_t attr;
    if (pthread_mutexattr_init(&attr) != 0) {
        perror("pthread_mutexattr_init");
        exit(EXIT_FAILURE);
    }
    // 设置互斥锁类型为递归互斥锁
    if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
        perror("pthread_mutexattr_settype");
        pthread_mutexattr_destroy(&attr);
        exit(EXIT_FAILURE);
    }

    pthread_mutex_init(&rtm->mutex, &attr);
    pthread_cond_init(&rtm->cond, NULL);
    rtm->owner = (pthread_t)0;
    rtm->count = 0;
    return PIKA_RES_OK;
#elif PIKA_FREERTOS_ENABLE
#if 0 //旧写法
    // rtm->mutex = xSemaphoreCreateMutex();
    rtm->mutex = xSemaphoreCreateBinary();
    if (rtm->mutex == NULL) {
        LOG("<%s>  xSemaphoreCreateBinary fail.\n", __func__ );
        return PIKA_RES_ERR_RUNTIME_ERROR;  // 初始化失败
    }
    LOG("<%s>  xSemaphoreCreateBinary succ.\n", __func__ );
    rtm->owner = NULL;
    rtm->count = 0;

    // 初始状态下信号量可用
    if (xSemaphoreGive(rtm->mutex) != pdTRUE) {
        vSemaphoreDelete(rtm->mutex);  // 清理
        return PIKA_RES_ERR_RUNTIME_ERROR;  // 给信号量失败
    }

    return PIKA_RES_OK;  // 初始化成功
#endif
    rtm->mutex = xSemaphoreCreateRecursiveMutex();
    if (rtm->mutex == NULL) {
        return PIKA_RES_ERR_MEMORY_ERROR;  // 初始化失败
    }
    return PIKA_RES_OK;  // 初始化成功
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}

// 带超时的递归互斥锁加锁
int pika_platform_thread_rlock_acquire(pika_platform_thread_rlock_t *rtm, pika_bool block, pika_float timeout) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)    
    ArgType timout_type = arg_getType(timeout);
    pika_float timeout_f;
    int result;

    
    if (!(timout_type == ARG_TYPE_FLOAT || timout_type == ARG_TYPE_INT || timout_type == ARG_TYPE_NONE)){
        return PIKA_RES_ERR_INVALID_PARAM;
    }

    pika_GIL_EXIT();
    pthread_mutex_lock(&rtm->mutex);
    pika_GIL_ENTER();

    if (rtm->owner == pthread_self()) {
        // 如果当前线程已经持有锁，则递归深度加1
        rtm->count++;
        // printf("rtm->count = %d\n", rtm->count);
        pthread_mutex_unlock(&rtm->mutex);
        // printf("succ\n");
        return PIKA_RES_OK;
    }
    


    if (timout_type == ARG_TYPE_FLOAT || timout_type == ARG_TYPE_INT){
        // printf("==== #01\n");
        if (timout_type == ARG_TYPE_FLOAT){
            timeout_f = arg_getFloat(timeout);
        }
        if (timout_type == ARG_TYPE_INT){
            int timeout_d = arg_getInt(timeout);
            timeout_f = (pika_float)timeout_d;
            // printf("==== #04  %lf\n", timeout_f);
        }
        if (timeout_f < 0.0f){
            return PIKA_RES_ERR_INVALID_PARAM;
        }
        
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);  // 获取当前时间

        // 将浮点数秒转换为秒和纳秒
        long sec = (long)timeout_f;
        long nsec = (long)((timeout_f - (pika_float)sec) * 1000000000.0);

        ts.tv_sec += sec;
        ts.tv_nsec += nsec;

        // 如果纳秒数超过 1 秒，则需要调整秒数和纳秒数
        if (ts.tv_nsec >= 1000000000) {
            ts.tv_nsec -= 1000000000;  // 减去 1 秒的纳秒数
            ts.tv_sec += 1;            // 增加 1 秒
        }

        // 等待直到获得锁或超时
        while (rtm->owner != (pthread_t)0) {
            pika_GIL_EXIT();
            result = pthread_cond_timedwait(&rtm->cond, &rtm->mutex, &ts);
            pika_GIL_ENTER();

            if (result != 0) {
                pthread_mutex_unlock(&rtm->mutex);
                return PIKA_RES_ERR_RUNTIME_ERROR;
            }
        }
        // 设置当前线程为锁的持有者
        rtm->owner = pthread_self();
        rtm->count = 1;
        pthread_mutex_unlock(&rtm->mutex);
        return PIKA_RES_OK;
        
    
    }
    else if (timout_type == ARG_TYPE_NONE){
        
        if (block) {
            // 永久等待
            while (rtm->owner != (pthread_t)0) {
                pika_GIL_EXIT();
                result = pthread_cond_wait(&rtm->cond, &rtm->mutex);
                pika_GIL_ENTER();

                if (result != 0) {
                    pthread_mutex_unlock(&rtm->mutex);
                    return PIKA_RES_ERR_RUNTIME_ERROR;
                }
            }
            // 设置当前线程为锁的持有者
            rtm->owner = pthread_self();
            rtm->count = 1;
            pthread_mutex_unlock(&rtm->mutex);
            return PIKA_RES_OK;

        }
        else{
            // 非阻塞模式
            if (rtm->owner == (pthread_t)0) {
                // 如果没有其他线程持有锁，获取锁
                rtm->owner = pthread_self();
                rtm->count = 1;
                pthread_mutex_unlock(&rtm->mutex);
                return PIKA_RES_OK;
            } else {
                // 如果已经有其他线程持有锁，立即返回 -1
                pthread_mutex_unlock(&rtm->mutex);
                return PIKA_RES_ERR_RUNTIME_ERROR;
            }
        }
    }
    else{
        return PIKA_RES_ERR_INVALID_PARAM;
    }


#elif PIKA_FREERTOS_ENABLE
    
    TickType_t ticksToWait;
    if (block){
        // 处理不同类型的timeout
        if (timeout > 0.0f) {
            // 浮点型，大于0：带阻塞超时的功能
            ticksToWait = (TickType_t)(timeout * configTICK_RATE_HZ);
        } else if (timeout == 0.0f) {
            // 等于0：立即返回获取锁的结果，不阻塞
            ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
        } else {
            ticksToWait = portMAX_DELAY;
        }
    }
    else{
        ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
    }

    int result;
    
    // 尝试获取信号量，支持超时
    pika_GIL_EXIT();
    result = xSemaphoreTakeRecursive(rtm->mutex, ticksToWait);
    pika_GIL_ENTER();

    if (result == pdTRUE){
        return PIKA_RES_OK;
    }
    else if (result == pdFALSE && ticksToWait > 0) {
        return PIKA_RES_ERR_TIMEOUT;
    }
    else{
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }

#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}

// 释放递归互斥锁
int pika_platform_thread_rlock_release(pika_platform_thread_rlock_t *rtm) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    pthread_t self = pthread_self();

    pika_GIL_EXIT();
    pthread_mutex_lock(&rtm->mutex);
    pika_GIL_ENTER();

    // printf("rtm->owner = %lu\n", rtm->owner);
    if (rtm->owner != self) {
        perror("Attempt to unlock a mutex not owned by the current thread");
        pthread_mutex_unlock(&rtm->mutex);
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }

    rtm->count--;
    if (rtm->count == 0) {
        rtm->owner = (pthread_t)0;
        pthread_cond_signal(&rtm->cond);
        // printf("rtm->owner = %lu\n", rtm->owner);
    }

    pthread_mutex_unlock(&rtm->mutex);
    return PIKA_RES_OK;
#elif PIKA_FREERTOS_ENABLE

    int result;
    result = xSemaphoreGiveRecursive(rtm->mutex);
    if (result == pdTRUE) {
        return PIKA_RES_OK;  // 成功
    } else {
        return PIKA_RES_ERR_RUNTIME_ERROR;  // 失败
    }

#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}


// 销毁递归互斥锁
void pika_platform_thread_rlock_destroy(pika_platform_thread_rlock_t *rtm) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    pthread_cond_destroy(&rtm->cond);
    pthread_mutex_destroy(&rtm->mutex);
#elif PIKA_FREERTOS_ENABLE
    if (rtm != NULL && rtm->mutex != NULL) {
        vSemaphoreDelete(rtm->mutex);
    }
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}

// 检查递归互斥锁是否已被当前线程获取
int pika_platform_thread_rlock_locked(pika_platform_thread_rlock_t *rtm) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    pthread_t self = pthread_self();
    pika_GIL_EXIT();
    pthread_mutex_lock(&rtm->mutex);
    pika_GIL_ENTER();
    int is_locked = (rtm->owner == self && rtm->count > 0);

    pthread_mutex_unlock(&rtm->mutex);

    return is_locked;
#elif PIKA_FREERTOS_ENABLE
    #if 1
    // 获取当前持有递归互斥锁的任务句柄
    TaskHandle_t xMutexOwner = xSemaphoreGetMutexHolder(rtm->mutex);
    return xMutexOwner != NULL ? 1 : 0;
    // 如果返回的任务句柄不是 NULL，则表示递归互斥锁已经被上锁
    #endif
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}




// 检查递归互斥锁是否已被当前线程获取
int pika_platform_thread_rlock_owned(pika_platform_thread_rlock_t *rtm) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
    pthread_t self = pthread_self();
    int is_owned = (rtm->owner == self);
    return is_owned;
#elif PIKA_FREERTOS_ENABLE
   
    // 获取当前任务句柄
    TaskHandle_t xCurrentTask = xTaskGetCurrentTaskHandle();
    // 获取拥有递归互斥锁的任务句柄
    TaskHandle_t xMutexOwner = xSemaphoreGetMutexHolder(rtm->mutex);
    // 比较当前任务句柄和拥有锁的任务句柄
    return xMutexOwner == xCurrentTask ? 1 : 0;

#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}




//----------------------------- semaphore -------------------------------
// 初始化计数信号量
int pika_platform_thread_semaphore_counting_init(pika_platform_thread_semaphore_t *sem, int maxcnt, int value) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
   
#elif PIKA_FREERTOS_ENABLE

    sem->semaphore = xSemaphoreCreateCounting(maxcnt, value);
    // rtm->mutex = xSemaphoreCreateBinary();
    if (sem->semaphore == NULL) {
        return PIKA_RES_ERR_MEMORY_ERROR;  // 初始化失败
    }

    return PIKA_RES_OK;  // 初始化成功
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}

// 初始化互斥信号量
int pika_platform_thread_semaphore_mutex_init(pika_platform_thread_semaphore_t *sem) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
   
#elif PIKA_FREERTOS_ENABLE

    sem->semaphore = xSemaphoreCreateMutex();
    if (sem->semaphore == NULL) {
        return PIKA_RES_ERR_MEMORY_ERROR;  // 初始化失败
    }

    return PIKA_RES_OK;  // 初始化成功
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}

// 初始化二值信号量
int pika_platform_thread_semaphore_binary_init(pika_platform_thread_semaphore_t *sem) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
   
#elif PIKA_FREERTOS_ENABLE

    sem->semaphore = xSemaphoreCreateBinary();
    if (sem->semaphore == NULL) {
        return PIKA_RES_ERR_MEMORY_ERROR;  // 初始化失败
    }
    
    // 初始状态下信号量可用
    if (xSemaphoreGive(sem->semaphore) != pdTRUE) {
        vSemaphoreDelete(sem->semaphore);  // 清理
        return PIKA_RES_ERR_MEMORY_ERROR;  // 给信号量失败
    }

    return PIKA_RES_OK;  // 初始化成功
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}



// 带超时的信号量获取
int pika_platform_thread_semaphore_acquire(pika_platform_thread_semaphore_t *sem, pika_bool block, pika_float timeout) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)    

#elif PIKA_FREERTOS_ENABLE
    TickType_t ticksToWait;
    if (block){
        // 处理不同类型的timeout
        if (timeout > 0.0f) {
            // 浮点型，大于0：带阻塞超时的功能
            ticksToWait = (TickType_t)(timeout * configTICK_RATE_HZ);
        } else if (timeout == 0.0f) {
            // 等于0：立即返回获取锁的结果，不阻塞
            ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
        } else {
            ticksToWait = portMAX_DELAY;
        }
    }
    else{
        ticksToWait = 0;  // FreeRTOS使用0表示非阻塞
    }
    pika_GIL_EXIT();
    BaseType_t result =  xSemaphoreTake(sem->semaphore, ticksToWait);
    pika_GIL_ENTER();
    if (result == pdTRUE){
        return PIKA_RES_OK;
    }
    else if (result == pdFALSE && ticksToWait > 0) {
        return PIKA_RES_ERR_TIMEOUT;
    }
    else{
        return PIKA_RES_ERR_RUNTIME_ERROR;
    }

#elif PIKA_RTTHREAD_ENABLE
    return rt_mutex_take((m->mutex), (rt_tick_t)(timeout * RT_TICK_PER_SECOND));

#elif PIKA_ZEUSOS_ENABLE
    return zos_mutex_lock(m->mutex, (uint32_t)(timeout * 1000.0f));

#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
    return PIKA_RES_ERR_RUNTIME_ERROR;
#endif
}



// 释放信号量
int pika_platform_thread_semaphore_release(pika_platform_thread_semaphore_t *sem) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)

#elif PIKA_FREERTOS_ENABLE
    
    int result = pdFALSE;
    result = xSemaphoreGive(sem->semaphore);
    if (result == pdTRUE) {
        return PIKA_RES_OK;  // 成功
    } else {
        return PIKA_RES_ERR_RUNTIME_ERROR;  // 失败
    }

#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}


// 销毁信号量
void pika_platform_thread_semaphore_destroy(pika_platform_thread_semaphore_t *sem) {
#if defined(__linux) || (PIKA_WIN_PTHREAD_ENABLE)
#elif PIKA_FREERTOS_ENABLE
    if (sem != NULL && sem->semaphore != NULL) {
        vSemaphoreDelete(sem->semaphore);
    }
#elif PIKA_RTTHREAD_ENABLE
#elif PIKA_ZEUSOS_ENABLE
#else
    WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_);
#endif
}
